import axios from "axios";
// import { useMessage} from 'naive-ui';
// import qs from "qs";

import getSession from "@/utils/getSession";
const session = new getSession();
// axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? 'http://yeziji.xyz/forum' : '/forum' //测试
// axios.defaults.baseURL = 'http://yeziji.xyz/forum' //正式
//axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? "http://110.40.213.24:8876" : "http://localhost:9999"
//post请求头
// axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
// axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
//设置超时
axios.defaults.timeout = 300000;
// 请求拦截  在请求头中获取token
axios.interceptors.request.use(
  (config) => {
    // 添加token
    const token = session.getStorage();
    if (token !== null) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 响应拦截
axios.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  (error) => {
    console.error(`异常请求：${JSON.stringify(error.message)}`);
  }
);

// TODO：对登录信息等进行校验

let prefix = "";
if (location.protocol === "https:") {
  // is https
  prefix = "https:";
} else {
  // is http
  prefix = "http:";
}
export default {
  // 请求地址 前缀,
  forumBase:
    process.env.NODE_ENV === "production"
      ? prefix + "//localhost:9999"
      : "/blog",
  post(url, data) {
    return new Promise((resolve, reject) => {
      axios({
        method: "post",
        url,
        data: JSON.stringify(data),
      })
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  get(url, data) {
    return new Promise((resolve, reject) => {
      axios({
        method: "get",
        url,
        params: data,
      })
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  // 以表单格式提交 带权限认真 以及 图片上传边界
  postForm(url, formData, token) {
    return new Promise((resolve, reject) => {
      axios({
        method: "post",
        url,
        headers: {
          // 设置边界
          "Content-Type":
            "multipart/form-data;boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
          Authorization: token,
        },
        data: formData,
      })
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },

  delArticle(url, data, token) {
    return new Promise((resolve, reject) => {
      axios({
        method: "get",
        url,
        headers: {
          Authorization: token,
        },
        params: data,
      })
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },

  // 登录json
  postFormByLogin(url, formData) {
    return new Promise((resolve, reject) => {
      axios({
        method: "post",
        url,
        headers: {
          "Content-Type": "application/json",
        },
        data: formData,
      })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },

  // 注册表单
  postFormByRegistry(url, formData) {
    return new Promise((resolve, reject) => {
      axios({
        method: "post",
        url,
        headers: {
          "Content-Type": "multipart/form-data",
        },
        data: formData,
      })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },

  getCaptchaImg(url, data) {
    return new Promise((resolve, reject) => {
      axios({
        method: "get",
        url,
        params: data,
        responseType: "blob",
      })
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },

  getBody(url, data) {
    return new Promise((resolve, reject) => {
      axios({
        method: "get",
        url,
        data: data,
      })
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },

  restFul(url, query, data) {
    if (query) {
      let hasFul = false;
      let pattern = /{.*?}/g;
      for (let key in query) {
        let txtKeys = url.match(pattern);
        if (txtKeys) {
          for (let txtKey of txtKeys) {
            let tk = txtKey.replace("{", "").replace("}", "");
            if (tk === key) {
              url = url.replace(txtKey, query[key]);
              hasFul = true;
            }
          }
        } else {
          throw new Error(
            "需要定义对应 restFul 参数，如：.../xx/{id}，对应入参 {id: 123}。请确保 url 声明了指定入参{param}"
          );
        }
      }
      if (!hasFul) {
        throw new Error(
          "请确保 ../xx/{key} 中入参 query 对象拥有 对应 {key:value}"
        );
      }
    }
    return new Promise((resolve, reject) => {
      axios({
        method: "get",
        url: url,
        params: data,
      })
        .then((res) => {
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },

  parseFormData(data) {
    let fd = new FormData();
    if (data && data instanceof Object) {
      for (let key in data) {
        fd.append(key, data[key]);
      }
    }
    return fd;
  },
};
